import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PurchaseOrderService {

  /**
   * 采购单查询
   */
  public getURL = '/purchase/list';
  /**
   * 采购单删除
   */
  public deleteURL = '/purchase/delete';
  /**
   * 采购单导出
   */
  public exportURL = '/purchase/getOrderExcel';

  constructor(public httpClient: HttpClient) {
  }

  /**
   * 采购单查询
   */
  public getList(json: any | null): Observable<any> {
    const jsons = {...json};
    if (jsons.dateFormat.length !== 0) {
      jsons.beginTime = this.shiftDate(jsons.dateFormat[0]);
      jsons.endTime = this.shiftDate(jsons.dateFormat[1]);
      delete jsons.dateFormat;
    }
    return this.httpClient.post(this.getURL, jsons);
  }

  /**
   * 采购单删除
   */
  public delete(id: any | null): Observable<any> {
    return this.httpClient.post(this.deleteURL, {id});
  }

  /**
   * 时间格式转换 年月日
   */
  shiftDate(date: any) {
    const d = new Date(date);
    return d.getFullYear() + '-' + this.p((d.getMonth() + 1)) + '-' + this.p(d.getDate());
  }

  /**
   * 补0
   */
  p(s: any) {
    return s < 10 ? '0' + s : s;
  }

  // 导出
  public async httpExportOrder(params: any) {
    return this.httpClient.get(this.exportURL, {params}).toPromise();
  }
}
